package com.education.platform.management.push;


import com.education.platform.common.util.StringUtils;
import com.education.platform.dao.ArticleDao;
import com.education.platform.dao.CourseDao;
import com.education.platform.dao.UserBaseDao;
import com.education.platform.dao.UserOrderDao;
import com.education.platform.dao.entity.ArticleDO;
import com.education.platform.dao.entity.CourseDO;
import com.education.platform.dao.entity.UserBaseDO;
import com.education.platform.management.enums.PushTypeEnum;
import com.education.platform.management.push.android.AndroidCustomizedcast;
import com.education.platform.management.push.ios.IOSCustomizedcast;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 消息推送
 *
 * @author tomato
 */
@Component
public class PushUtil {

    private final static Logger LOGGER = LoggerFactory.getLogger(PushUtil.class);

    private static String appkey = "5efc4fdd895cca471200002b";
    private static String appMasterSecret = "udft8z3edqivzu3sfn3ziaf9lsnacvuf";

    private static String appkeyIos = "5efc502d570df32638000124";
    private static String appMasterSecretIos = "ymkttdrswtjlpucuhyswozns0o5dfncq";
    private String timestamp = null;
    private PushClient client = new PushClient();

    private static final String ALIAS_TYPE = "phone";
    private static Boolean TEST;

    private static volatile PushUtil pushUtil;

    public static Boolean getTEST() {
        return TEST;
    }

    @Value("${umeng.test}")
    public void setTEST(Boolean TEST) {
        PushUtil.TEST = TEST;
    }

    @Autowired
    private UserBaseDao userBaseDao;
    @Autowired
    private CourseDao courseDao;
    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private UserOrderDao userOrderDao;


    private String buildText(UserBaseDO user, PushTypeEnum typeEnum, String extraId, String extraType) {
        if (PushTypeEnum.GIVE_BEANS.eq(typeEnum)) {
            return user.getNickName() + "，" + extraId + "历史豆已到账，请注意查收";
        } else if (PushTypeEnum.COMMENT.eq(typeEnum)) {
            if ("course".equals(extraType)) {
                CourseDO courseDO = courseDao.getById(Integer.parseInt(extraId));
                return user.getNickName() + "，您在【" + courseDO.getCourseName() + "】中的评论入选精选评论咯~快去查看吧";
            } else {
                ArticleDO articleDO = articleDao.getById(Integer.parseInt(extraId));
                return user.getNickName() + "，您在【" + articleDO.getTitle() + "】中的评论入选精选评论咯~快去查看吧";
            }
        } else if (PushTypeEnum.SEND.eq(typeEnum)) {
            return "您购买的【" + extraType + "】已发货，快点击查看吧";
        } else if (PushTypeEnum.FEED_BACK.eq(typeEnum)) {
            return user.getNickName() + "，您的反馈意见我们已经收到并对此进行了回复，赶快点击查看吧~";
        }
        return "";
    }

    /**
     * 推送--安卓
     *
     * @param alias
     * @param typeEnum
     * @param extraId
     * @param extraType
     */
    private void sendAndroidCustomizedcast(String alias, PushTypeEnum typeEnum, String extraId, String extraType, String text, String title) {
        try {
            AndroidCustomizedcast customizedcast = new AndroidCustomizedcast(appkey, appMasterSecret);
            customizedcast.setAlias(alias, ALIAS_TYPE);
            customizedcast.setDisplayType(AndroidNotification.DisplayType.NOTIFICATION);
            customizedcast.setTicker(typeEnum.getTitle());
            if (StringUtils.isNotEmpty(title)) {
                customizedcast.setTitle(title);
            } else {
                customizedcast.setTitle(typeEnum.getTitle());
            }
            if (StringUtils.isEmpty(text)) {
                customizedcast.setText(typeEnum.getText());
            } else {
                customizedcast.setText(text);
            }
            customizedcast.goCustomAfterOpen("custom");
            customizedcast.setCustomField(typeEnum.getValue());
            if (extraId != null && !PushTypeEnum.GIVE_BEANS.eq(typeEnum)) {
                customizedcast.setExtraField("id", extraId);
            }
            if (extraType != null && PushTypeEnum.COMMENT.eq(typeEnum)) {
                customizedcast.setExtraField("type", extraType);
            }
            if (TEST) {
                customizedcast.setTestMode();
            } else {
                customizedcast.setProductionMode();
            }
//            customizedcast.goAppAfterOpen();
            //厂商通道相关参数
//        customizedcast.setChannelActivity("your channel activity");
//        customizedcast.setChannelProperties("abc");
            client.send(customizedcast);
            LOGGER.info("安卓推送成功:alias=" + alias);
        } catch (Exception e) {
            LOGGER.error("安卓推送失败：" + e.getMessage());
        }

    }

    /**
     * 推送==ios
     *
     * @param alias
     * @param typeEnum
     * @param extraId
     * @param extraType
     */
    private void sendIOSCustomizedcast(String alias, PushTypeEnum typeEnum, String extraId, String extraType, String text, String title) {
        try {
            IOSCustomizedcast customizedcast = new IOSCustomizedcast(appkeyIos, appMasterSecretIos);
            customizedcast.setAlias(alias, ALIAS_TYPE);
            //customizedcast.setAlert("IOS 个性化测试");
            //alert的值设置为字典
            customizedcast.setAlert(StringUtils.isEmpty(title) ? typeEnum.getTitle() : title,
                    "", StringUtils.isEmpty(text) ? typeEnum.getText() : text);
            customizedcast.setBadge(0);
            customizedcast.setSound("default");
            customizedcast.setCustomizedField("custom", typeEnum.getValue());
            if (extraId != null && !PushTypeEnum.GIVE_BEANS.eq(typeEnum)) {
                customizedcast.setCustomizedField("id", extraId);
            }
            if (extraType != null && PushTypeEnum.COMMENT.eq(typeEnum)) {
                customizedcast.setCustomizedField("type", extraType);
            }
            if (TEST) {
                customizedcast.setTestMode();
            } else {
                customizedcast.setProductionMode();
            }
            client.send(customizedcast);
            LOGGER.info("IOS推送成功:alias=" + alias);
        } catch (Exception e) {
            LOGGER.error("IOS推送失败：" + e.getMessage());
        }

    }


    /**
     * 指定推送
     *
     * @param userId
     * @param typeEnum
     * @param extraId
     * @param extraType
     */
    public void push(Integer userId, PushTypeEnum typeEnum, String extraId, String extraType) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                UserBaseDO user = userBaseDao.getById(userId);
                if (user == null || user.getDevice() == null || user.getId() == null) {
                    return;
                }
                String text = buildText(user, typeEnum, extraId, extraType);
                LOGGER.info(String.format("推送：userId【%s】，typeEnum=【%s】,extraId[%s],extraType[%s]",
                        userId, typeEnum.getValue(), extraId, extraType));
                switch (user.getDevice()) {
                    case "ios":
                        sendIOSCustomizedcast(String.valueOf(user.getId()), typeEnum, extraId, extraType, text, null);
                        break;
                    case "android":
                        sendAndroidCustomizedcast(String.valueOf(user.getId()), typeEnum, extraId, extraType, text, null);
                        break;
                }
            }
        }).start();

    }

    /**
     * 全部推送
     *
     * @param typeEnum
     * @param extraId
     * @param
     */
    public void push(PushTypeEnum typeEnum, String extraId, String title, String text) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                int start = 0;
                int pageSize = 500;
                for (; ; ) {
                    List<UserBaseDO> androidDevices = userBaseDao.getPushMessage("android", start, pageSize);
                    if (CollectionUtils.isEmpty(androidDevices)) {
                        break;
                    }
                    start = start + pageSize - 1;
                    String alias = androidDevices.parallelStream().map(i -> String.valueOf(i.getId())).collect(Collectors.joining(","));
                    sendAndroidCustomizedcast(alias, typeEnum, extraId, null, text, title);

                }
                start = 0;
                pageSize = 500;
                for (; ; ) {
                    List<UserBaseDO> iosDevices = userBaseDao.getPushMessage("ios", start, pageSize);
                    if (CollectionUtils.isEmpty(iosDevices)) {
                        break;
                    }
                    start = start + pageSize - 1;
                    String alias = iosDevices.parallelStream().map(i -> String.valueOf(i.getId())).collect(Collectors.joining(","));
                    sendIOSCustomizedcast(alias, typeEnum, extraId, null, text, title);
                }
            }
        }).start();


    }

    public static void main(String[] args) {
//        PushUtil pushUtil = PushUtil.getInstance();
//        pushUtil.pushMessage("13548005539","1","test2","test23232");

    }


}
